package com.ymj.netty.server;

import com.ymj.netty.server.handler.BizServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 *  @Description:
 *  @author: yanmj
 *  @Date: 2020-06-07
 */
@Component
public class Server{

    @Value("${netty.server.port}")
    private int PORT;

    public void start() throws Exception {
        EventLoopGroup boss = null;
        EventLoopGroup worker = null;
        try{
            boss = new NioEventLoopGroup(1);
            worker = new NioEventLoopGroup(1);

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .localAddress(new InetSocketAddress(PORT))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(65535,Delimiters.lineDelimiter()));
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new IdleStateHandler(60,45,20, TimeUnit.SECONDS));
                            socketChannel.pipeline().addLast(new BizServerHandler());
                            socketChannel.pipeline().addLast(new StringEncoder());

                        }
                    });
            ChannelFuture future = bootstrap.bind().sync();
            System.out.println("服务器已启动");

//            //将服务注册到zookeeper
//            InetAddress inetAddress = InetAddress.getLocalHost();
//            CuratorFramework zookeeperClient = ZookeeperFactory.create();
//            zookeeperClient.create().withMode(CreateMode.EPHEMERAL).forPath(Constans.SERVER_PATH+inetAddress.getHostAddress());

            future.channel().closeFuture().sync();
        }  finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

}
